import { _decorator, Component, Node, Graphics, Color, view, game, BlockInputEvents, UITransform } from 'cc'
const { ccclass, property } = _decorator

import EventManager from '../../Runtime/EventManager'

import { DIRECTION } from '../../Enums'

// 状态
export enum DrawState {
  IDLE = 'IDLE',
  SHAKE = 'SHAKE',
}


@ccclass('ShakeManager')
export class ShakeManager extends Component {
  private state: DrawState = DrawState.IDLE
  private oldTime: number = 0
  private nodePos: {x: number, y: number} = {x: 0, y: 0}
  private direction: DIRECTION = DIRECTION.TOP


  onLoad() {
    EventManager.Instance.on('SHAKE', this.shake, this)
  }

  onDestroy() {
    EventManager.Instance.off('SHAKE', this.shake)
  }

  update() {
    if(this.state === DrawState.SHAKE) {
       /***
   * 正弦震动
   * y= A * sin *(wx + f)
   */
      //振幅
      const shakeAmount = 1.6
      //持续时间
      const duration = 200
      //频率
      const frequency = 6
      //当前时间
      const curSecond = (game.totalTime - this.oldTime) / 1000
      //总时间
      const totalSecond = duration / 1000

      const offset = shakeAmount * Math.sin(frequency * Math.PI * 2 * curSecond)

      if(this.direction === DIRECTION.TOP) {
        this.node.setPosition(this.nodePos.x, this.nodePos.y - offset)
      } else if(this.direction === DIRECTION.BOTTOM) {
        this.node.setPosition(this.nodePos.x, this.nodePos.y + offset)
      } else if(this.direction === DIRECTION.LEFT) {
        this.node.setPosition(this.nodePos.x - offset, this.nodePos.y)
      } else if(this.direction === DIRECTION.RIGHT) {
        this.node.setPosition(this.nodePos.x + offset, this.nodePos.y)
      }

      if(curSecond > totalSecond) {
        this.state = DrawState.IDLE
        this.node.setPosition(this.nodePos.x, this.nodePos.y)
      }
    }
  }


  shake(direction: DIRECTION) {
    if(this.state === DrawState.SHAKE) {
      return
    }
    // 开始震动
    this.oldTime = game.totalTime
    this.state = DrawState.SHAKE
    this.direction = direction // 震动方向
    let {x, y} = this.node.getPosition()
    this.nodePos = {x, y}
  }

  // 停止震动
  stop() {
    this.state = DrawState.IDLE
  }
}
